//
//  JSBridge_JS.m
//  JSBridge
//
//  Created by Tianlong on 2019/9/7.
//  Copyright © 2019 Tianlong. All rights reserved.
//

#import "JSBridge_JS.h"

@implementation JSBridge_JS
NSString * WebBridge_JS() {
#define __wvjb_js_func__(x) #x
    
    // BEGIN preprocessorJSCode
    static NSString * preprocessorJSCode = @__wvjb_js_func__((function() {
        
        if (window.WebViewJavascriptBridge) {
            return;
        }
        
        window.WebViewJavascriptBridge = {
        callHandler: callHandler,
        _fetchQueue: _fetchQueue,
        };
        
        var messagingIframe;
        var sendMessageQueue = [];
        var messageHandlers = {};
        
        var CUSTOM_PROTOCOL_SCHEME = 'https';
        var QUEUE_HAS_MESSAGE = '__bridge_message__';
        
        function callHandler(handlerName, data, responseCallback) {
            _doSend({ handlerName:handlerName, data:data }, responseCallback);
        }
        
        function _doSend(message,responseCallback) {
            sendMessageQueue.push(message);
            messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
        }
        
        function _fetchQueue() {
            var messageQueueString = JSON.stringify(sendMessageQueue);
            sendMessageQueue = [];
            return messageQueueString;
        }
        
        messagingIframe = document.createElement('iframe');
        messagingIframe.style.display = 'none';
        messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
        document.documentElement.appendChild(messagingIframe);
        
        
        /*
         对应：setupWebViewJavascriptBridge 中
         if (window.BridgeCallbacks) { return window.BridgeCallbacks.push(callback); }
         window.BridgeCallbacks = [callback];
         */
        setTimeout(_callBridgeCallbacks, 0);
        function _callBridgeCallbacks() {
            var callbacks = window.BridgeCallbacks;
            delete window.BridgeCallbacks;
            for (var i=0; i<callbacks.length; i++) {
                callbacks[i](WebViewJavascriptBridge);
            }
        }
        
    })();
                                                             ); // END preprocessorJSCode
    
#undef __wvjb_js_func__
    return preprocessorJSCode;
};

@end
